﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SpaceSquirrel.Automation
{
	public class FireballAutomation : SpriteAutomation
	{
		private const double FIREBALL_VELOCITY = 1.5;

		private int counter;
		private int startX;
		private int startY;
		private bool goLeft;
		private double vx;
		private double vy;
		private int predictedX;

		public FireballAutomation(Sprite sprite)
			: base(sprite)
		{
			this.sprite = sprite;
			this.counter = 0;
			this.startX = sprite.x;
			this.startY = sprite.y;
			this.goLeft = sprite.lastDirection == "left";
			this.vx = -FIREBALL_VELOCITY;
			this.vy = 0;
		}

		public override void DoStuff(PlayScene scene)
		{
			if (this.counter == 0)
			{
				int dx = scene.Player.x - this.startX;
				int dy = scene.Player.y - this.startY;

				if (dx == 0)
				{
					dx = 1;
				}

				double m = 1.0 * dy / dx;
				if (m > 1)
				{
					m = 1;
				}
				else if (m < -1)
				{
					m = -1;
				}

				// TODO: verify that the C# and Python implementations of Tan return the angle in the same range. 
				double ang = Math.Atan(m);
				this.vx = FIREBALL_VELOCITY * Math.Cos(ang);
				this.vy = FIREBALL_VELOCITY * Math.Sin(ang);
				if (this.goLeft)
				{
					this.vx *= -1;
				}
			}
			else
			{
				if (this.predictedX != this.sprite.x)
				{
					// umm...
					// so this code in the original said self.sprite.dead
					// but did not assign True. This was clearly a bug.
					// If the fireballs keep living beyond colliding with the wall, 
					// then uncomment the line here.
					// If not, then just delete this whole else. And possibly the predicted stuff as well.

					// this.sprite.dead = true;
				}
			}

			this.sprite.dx += this.vx;
			this.sprite.dy += this.vy;

			this.predictedX = (int)(this.sprite.dx + this.sprite.modelX);

			if (this.sprite.collideWall)
			{
				// This probably fulfills the condition of the comment above.
				this.sprite.dead = true;
			}

			this.counter++;
		}
	}
}
